import { createRouter, createWebHistory } from "vue-router"
import Login from "@mars/pages/login/App.vue"
import Home from "@mars/pages/zhts/App.vue"
import { getToken } from "@mars/utils/auth"
import { nextTick } from "vue"

const router = createRouter({
  routes: [
    {
      path: "/login",
      name: "login",
      component: Login,
      meta: { title: "登录 - 电磁声波三维可视化系统" }
    },
    {
      path: "/",
      name: "index",
      component: Home,
      meta: {
        requiresAuth: true,
        title: "电磁声波三维可视化系统"
      }
    },
    {
      path: "/index", // 额外路径
      redirect: "/" // 重定向到主路径
    }
  ],
  history: createWebHistory()
})

const whiteList = ["/login", "/register", "/social-callback"]

// 添加路由守卫
router.beforeEach(async (to, from, next) => {
  await nextTick()
  // 确保每次都会执行
  // const token = getToken()

  const token = getToken()
  if (token) {
    if (to.path === "/login") {
      next({ path: "/" })
    } else if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next()
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({
        path: "/login",
        query: { redirect: to.fullPath }
      }) // 否则全部重定向到登录页
    }
  }

})
export default router
